$(function () {
    const form = layui.form
    const layer = layui.layer
    initEditor()
    renderCate()

    function renderCate() {
        $.get('/my/article/cates').then(res => {
            $('select[name=cate_id]').html(template('tpl-cate', res))
            form.render()
        })
    }

    const $image = $('#cover')
    const options = {
        aspectRatio: 1,
        preview: '.preview-cover'
    }
    $image.cropper(options)

    $('#select-file').on('click', function () {
        $('#file').trigger('click')
    })

    $('#file').on('change', function () {
        const file = this.files[0]
        const src = window.URL.createObjectURL(file)
        $image.cropper('destroy').attr('src', src).cropper(options)
    })
    let state = '已发布'
    $('#pub-form').on('submit', function () {
        const formData = new FormData(this)
        formData.append('state', state)
        $image.cropper('getCroppedCanvas', {
            width: 200,
            height: 200
        }).toBlob(function (blob) {
            formData.append('cover_img', blob)
            $.ajax({
                method: 'post',
                url: '/my/article/add',
                data: formData,
                contentType: false,
                processData: false,
            }).then(res => {
                layer.msg('发布成功！')
                setTimeout(() =>{ // 延迟0.5秒后执行跳转
                    location.href = '/article/article-list.html'
                }, 500)
            })
        })
        return false
    })
})